import React, { useState } from 'react'
import useDialogState from '@/hooks/use-dialog-state'
import { type Rule } from '../data/schema'

type RulesDialogType = 'add' | 'edit' | 'delete' | 'batch-delete'

interface RulesContextType {
  open: RulesDialogType | null
  setOpen: (str: RulesDialogType | null) => void
  currentRow: Rule | null
  setCurrentRow: React.Dispatch<React.SetStateAction<Rule | null>>
}

const RulesContext = React.createContext<RulesContextType | null>(null)

interface Props {
  children: React.ReactNode
}

export default function RulesProvider({ children }: Props) {
  const [open, setOpen] = useDialogState<RulesDialogType>(null)
  const [currentRow, setCurrentRow] = useState<Rule | null>(null)

  return (
    <RulesContext value={{ open, setOpen, currentRow, setCurrentRow }}>
      {children}
    </RulesContext>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export const useRules = () => {
  const rolesContext = React.useContext(RulesContext)

  if (!rolesContext) {
    throw new Error('useRules has to be used within <RulesContext>')
  }

  return rolesContext
}
